const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');

const app = express();
const PORT = 3000;

// Middleware
app.use(cors());
app.use(express.json());

// Dynamic schema with flexible structure
function createSchema() {
  const schema = new mongoose.Schema({}, {
    strict: false,
    timestamps: { createdAt: true, updatedAt: false }
  });
  return schema;
}

// Dynamic model getter
function getModel(collectionName) {
  if (mongoose.models[collectionName]) {
    return mongoose.model(collectionName);
  }
  return mongoose.model(collectionName, createSchema(), collectionName);
}

// API endpoint
app.post('/api/save', async (req, res) => {
  try {
    const { url, collection, data } = req.body;
    
    // Connect to MongoDB using the provided URL
    await mongoose.connect(url, {
      useNewUrlParser: true,
      useUnifiedTopology: true
    });
    
    const Model = getModel(collection);
    const doc = new Model({ ...data });
    const result = await doc.save();
    
    res.json({ 
      success: true,
      insertedId: result._id
    });
  } catch (error) {
    console.error('Save error:', error);
    res.status(500).json({ 
      success: false,
      error: error.message 
    });
  }
});

// Start server
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});
